#include <pthread.h>
#include <string>
#include <iostream>
#include <cstring>
#include <functional>

using fun_t = std::function<void()>;

namespace ThreadModlue
{
    class Thread
    {
        void EnableDetach()
        {
            if (_isdetach || !_isruning)
                return;
            _isdetach = true;
        }
        void EnableRuning()
        {
            if (!_isruning)
                _isruning = true;
        }

    public:
        Thread(fun_t fn)
            : _isdetach(false),
              _isruning(false),
              _tid(-1),
              _fn(fn)
        {
            _name = "thread" + std::to_string(_number);
        }
        static void *routine(void *arg)
        {
            Thread *self = static_cast<Thread *>(arg);
            self->_fn();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, routine, this);
            if (n != 0)
            {
                std::cerr << "creat thread error:" << strerror(n) << std::endl;
                return false;
            }
            EnableRuning();
            if (_isdetach)
                EnableDetach();
            std::cout << "start success" << std::endl;
            // pthread_setname_np(_tid, _name.c_str());
            return true;
        }
        void Detach()
        {
            if (_isdetach)
                return;
            int n = pthread_detach(_tid);
            if (n != 0)
            {
                std::cerr << "detach thread error:" << strerror(n) << std::endl;
                return;
            }
            EnableDetach();
            std::cout << "Detach success" << std::endl;
        }
        void Stop()
        {
            if (!_isruning)
                return;
            int n = pthread_cancel(_tid);
            if (n != 0)
            {
                std::cerr << "stop thread error:" << strerror(n) << std::endl;
                return;
            }
            _isruning = false;
            std::cout << "Stop success" << std::endl;
        }
        bool Join()
        {
            if (_isdetach)
            {
                std::cout << "Thread Detach" << std::endl;
                return false;
            }
            int n = pthread_join(_tid, nullptr);
            if (n != 0)
            {
                std::cerr << "join thread error:" << strerror(n) << std::endl;
                return false;
            }
            std::cout << "join success" << std::endl;
            return true;
        }

        ~Thread()
        {
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isdetach;
        bool _isruning;
        fun_t _fn;

        static int _number; // 斟酌斟酌
    };
    int Thread::_number = 1;
}